// src/store/modules/user.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
export interface IUserState {
    loginState: boolean
    adminname: string
    token: string
    role: number
    checkedkeys: any[]
}
const initialState = {
    loginState: localStorage.getItem('loginState') === 'true',
    adminname: localStorage.getItem('adminname') || '',
    token: localStorage.getItem('token') || '',
    role: Number(localStorage.getItem('role')),
    checkedkeys: JSON.parse(localStorage.getItem('checkedkeys')!)
} as IUserState

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        changeLoginState(state, action: PayloadAction<boolean>) {
            localStorage.setItem('loginState', action.payload.toString())
            state.loginState = action.payload
        },
        changeAdminName(state, action: PayloadAction<string>) {
            localStorage.setItem('adminname', action.payload)
            state.adminname = action.payload
        },
        changeToken(state, action: PayloadAction<string>) {
            localStorage.setItem('token', action.payload)
            state.token = action.payload
        },
        changeRole(state, action: PayloadAction<number>) {
            localStorage.setItem('role', action.payload + '')
            state.role = action.payload
        },
        changeCheckedkeys(state, action: PayloadAction<any[]>) {
            localStorage.setItem('checkedkeys', JSON.stringify(action.payload))
            state.checkedkeys = action.payload
        }
    }
})
// 快捷导出方法，方便我们直接调用
export const { changeLoginState, changeAdminName, changeToken, changeRole, changeCheckedkeys } = userSlice.actions
export default userSlice.reducer